
$(function() {
	
    var $calendar = $('#calendar');
    var id = 10;
    
	$calendar.weekCalendar({
		timeslotsPerHour : 4,
		allowCalEventOverlap : true,
        businessHours :{start: 8, end: 18, limitDisplay: true },
		height : function($calendar) {
			return $(window).height() - $("h1").outerHeight();
		},
		eventRender : function(calEvent, $event) {
			if (calEvent.end.getTime() < new Date().getTime()) {
				$event.css("backgroundColor", "#aaa");
				$event.find(".wc-time").css({
							"backgroundColor" : "#999",
							"border" : "1px solid #888"
						});
			}
		},
        draggable : function(calEvent, $event) {
           return calEvent.readOnly != true;
        },
        resizable : function(calEvent, $event) {
            return calEvent.readOnly != true;
        },
		eventNew : function(calEvent, $event) {
            var $dialogContent = $("#event_edit_container");
            resetForm($dialogContent);
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField =  $dialogContent.find("select[name='end']").val(calEvent.end);
            var titleField = $dialogContent.find("input[name='title']");
            var subjectsField = $dialogContent.find("input[name='subjects']");
            var recurrenceField = $dialogContent.find("input[name='recurrence']");
            recurrenceField.click(function () {
            	if ($(this).is(':checked')) {
            		$("#event_recurrence").slideUp();
            	} else { 
            		$("#event_recurrence").slideDown();
            	}
            });
            $dialogContent.find("input[name='endDate']").datepicker();
                        
            
            $dialogContent.dialog({
                modal: true,
                title: "New Course",
                close: function() {
                   $dialogContent.dialog("destroy");
                   $dialogContent.hide();
                   $('#calendar').weekCalendar("removeUnsavedEvents");
                },
                buttons: {
                    save : function(){
                        calEvent.id = id;
                        id++;
                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.subjects = subjectsField.val();
                        calEvent.recurrence = recurrenceField.val();
                        $.ajax({
                        	   type: "POST",
                        	   url: "/admin/eventschedules",
                        	   cache: false,
                        	   data: {"object.startDate":calEvent.start.toString("yyyy-MM-dd"), 
                        				"object.endDate":calEvent.end.toString("yyyy-MM-dd"),
                        				"object.startTime":calEvent.start.toString("HH:mm"), 
                        				"object.endTime":calEvent.end.toString("HH:mm")},
                        	   success: function(msg){
                        	     alert( "Data Saved: " + msg );
                        	   },
                        	   error: function(req, msg, ex){
                          	     alert( "Data NOT Saved: " + msg + " " + ex);
                          	   }
                        	 });
                        $calendar.weekCalendar("removeUnsavedEvents");
                        $calendar.weekCalendar("updateEvent", calEvent);
                        $dialogContent.dialog("close");
                    },
                    cancel : function(){
                        $dialogContent.dialog("close");
                    }
                }
            }).show();
             
            $dialogContent.find(".date_holder").text(calEvent.start.getFullYear() + "-" + calEvent.start.getMonth() + "-" + calEvent.start.getDate());
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
            $(window).resize(); //fixes a bug in modal overlay size ??
            
            
		},
		eventDrop : function(calEvent, $event) {
		},
		eventResize : function(calEvent, $event) {
		},
		eventClick : function(calEvent, $event) {
            
          
            
            var $dialogContent = $("#event_edit_container");
            resetForm($dialogContent);
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField =  $dialogContent.find("select[name='end']").val(calEvent.end);
            var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
            var subjectsField = $dialogContent.find("input[name='subjects']").val(calEvent.subjects);
            var recurrenceField = $dialogContent.find("input[name='recurrence']").val(calEvent.recurrence);
            recurrenceField.click(function () {
            	if ($(this).is(':checked')) {
            		$("#event_recurrence").slideUp();
            	} else { 
            		$("#event_recurrence").slideDown();
            	}
            });
            $dialogContent.find("input[name='endDate']").datepicker();
            
            $dialogContent.dialog({
                modal: true,
                title: "Edit - " + calEvent.title,
                close: function() {
                   $dialogContent.dialog("destroy");
                   $dialogContent.hide();
                   $('#calendar').weekCalendar("removeUnsavedEvents");
                },
                buttons: {
                    save : function(){
                	  if(calEvent.readOnly) {
                		  $dialogContent.dialog("close");
                          return;
                      }
                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.subjects = subjectsField.val();
                        calEvent.recurrence = recurrenceField.val();
                        
               
                        $calendar.weekCalendar("updateEvent", calEvent);
                       
                    },
                    "delete" : function(){
                        $calendar.weekCalendar("removeEvent", calEvent.id);
                        $dialogContent.dialog("close");
                    },
                    cancel : function(){
                        $dialogContent.dialog("close");
                    }
                }
            }).show();
            
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField =  $dialogContent.find("select[name='end']").val(calEvent.end);
            $dialogContent.find(".date_holder").text(calEvent.start.getFullYear() + "-" + calEvent.start.getMonth() + "-" + calEvent.start.getDate());
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
		    $(window).resize(); //fixes a bug in modal overlay size ??
        
        },
		eventMouseover : function(calEvent, $event) {
		},
		eventMouseout : function(calEvent, $event) {
		},
		noEvents : function() {
            
		},
		data : function(start, end, callback) {
            callback(getEventData());
        }
	});
    
    function resetForm($dialogContent) {
         $dialogContent.find("input").val("");
         $dialogContent.find("textarea").val("");
         $dialogContent.find("input").attr('checked', null);
         $("#event_recurrence").hide();
    }
    
    function getEventData() {
        var year = new Date().getFullYear();
        var month = new Date().getMonth();
        var day = new Date().getDate();
        
        return {
            events : [
               {"id":1, "start": new Date(year, month, day, 12), "end": new Date(year, month, day, 13, 30),"title":"Lunch with Mike"},
               {"id":2, "start": new Date(year, month, day, 14), "end": new Date(year, month, day, 14, 45),"title":"Dev Meeting"},
               {"id":3, "start": new Date(year, month, day + 1, 17), "end": new Date(year, month, day + 1, 17, 45),"title":"Hair cut"},
               {"id":4, "start": new Date(year, month, day - 1, 8), "end": new Date(year, month, day - 1, 9, 30),"title":"Team breakfast"},
               {"id":5, "start": new Date(year, month, day + 1, 14), "end": new Date(year, month, day + 1, 15),"title":"Product showcase"},
               {"id":5, "start": new Date(year, month, day, 10), "end": new Date(year, month, day, 11),"title":"I'm read-only", readOnly : true}
            
            ]
        };
    }
    
    
    /*
     * Sets up the start and end time fields in the calendar event 
     * form for editing based on the calendar event being edited
     */
    function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {
            
       for(var i=0; i<timeslotTimes.length; i++) {
            var startTime = timeslotTimes[i].start; 
            var endTime = timeslotTimes[i].end;
            var startSelected = "";
            if(startTime.getTime() === calEvent.start.getTime()) {
                startSelected = "selected=\"selected\"";
            }
            var endSelected = "";
            if(endTime.getTime() === calEvent.end.getTime()) {
                endSelected = "selected=\"selected\"";
            }
            $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
            $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");
       
        }
        $endTimeOptions = $endTimeField.find("option"); 
        $startTimeField.trigger("change");
    }
   
   var $endTimeField = $("select[name='end']"); 
   var $endTimeOptions = $endTimeField.find("option"); 
    
   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function(){
        var startTime = $(this).find(":selected").val();
        var currentEndTime = $endTimeField.find("option:selected").val();
        $endTimeField.html(
            $endTimeOptions.filter(function(){
                return startTime < $(this).val();
            })
        );
        
        var endTimeSelected = false;
        $endTimeField.find("option").each(function() {
            if($(this).val() === currentEndTime) {
                $(this).attr("selected", "selected");
                endTimeSelected = true;
                return false;
            }
        });
        
        if(!endTimeSelected) {
           //automatically select an end date 2 slots away. 
           $endTimeField.find("option:eq(1)").attr("selected", "selected");
        }
        
    }); 
  

});